import {ActionSheetController, Events, IonicPage, NavController} from "ionic-angular";
import {Component, QueryList, ViewChildren} from "@angular/core";
import {CallNumber} from "@ionic-native/call-number";
import {RosterListProvider} from "../../../providers/activity/roster-list/roster-list.provider";
import {RosterFilterModel, RosterSortBy} from "../../../model/pages/activity/roster-filter/roster-filter.model";
import {AddStaffTrack, RosterItem, TrackStatus} from "../../../model/pages/activity/roster-list/roster-list-item.model";
import {ActivityClassify, ActivityStatus} from "../../../model/pages/activity/activity-filter/activity-filter.model";
import {ActivityListProvider} from "../../../providers/activity/activity-list/activity-list.provider";
import * as _ from 'lodash';
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {LoadingService} from "../../../services/common/loading.service";
import {Vs} from "./vs";
import {RosterCardComponent} from "../../../components/pages/activity/roster-card/roster-card.component";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

@IonicPage()
@Component({
    selector: 'page-roster-list',
    templateUrl: 'roster-list.html',
    providers: [CallNumber, RosterListProvider, LoadingService,
        ActivityListProvider, CallNumberService, ClientNoteEditProvider]
})
export class RosterListPage {

    constructor(private navCtrl: NavController,
                private actionSheetCtrl: ActionSheetController,
                private adpActionSheetCtrl: AdpActionSheetController,
                private events: Events,
                private callNumber: CallNumber,
                private rosterPro: RosterListProvider,
                private activityListPro: ActivityListProvider,
                private callNumberService: CallNumberService,
                private loadingService: LoadingService) {
    }

    @ViewChildren(RosterCardComponent) rosterCards: QueryList<RosterCardComponent>;

    //是否展开排序条件
    private isExpandSorter: boolean = false;
    //筛选条件
    private rosterFil: RosterFilterModel = new RosterFilterModel();
    //筛选条件（用作展示）
    private tempFil: RosterFilterModel = new RosterFilterModel();
    //客户活动名单
    private rosterList: RosterItem[] = [];
    //当前试图 0代表客户名单，1代表增员名单
    private currentView = 0;
    //列表数据是否加载完毕
    private isLoaded = false;
    //所有的活动类型
    private allType = [];
    //排序方式
    private sortByList = [{
        val: RosterSortBy.priority,
        label: '默认排序'
    }, {
        val: RosterSortBy.name,
        label: '姓名'
    }, {
        val: RosterSortBy.time,
        label: '活动开始时间'
    }];
    private vs;
    private totalNum = 0;
    private actionButtons = [{
        text: '未跟进',
        value: TrackStatus.notFollow
    }, {
        text: '已拨打',
        value: TrackStatus.contacted
    }, {
        text: '未接通',
        value: TrackStatus.notContacted
    }, {
        text: '客户不感兴趣',
        value: TrackStatus.notInterested
    }, {
        text: '待回电',
        value: TrackStatus.waitCallback
    }, {
        text: '已面谈',
        value: TrackStatus.overInterview
    }, {
        text: '已打印计划书',
        value: TrackStatus.overPrint
    }, {
        text: '已完成',
        value: TrackStatus.complete
    }];

    private actionButtons2 = [{
        text: '未跟进',
        value: AddStaffTrack.notFollow
    }, {
        text: '跟进中',
        value: AddStaffTrack.process
    }, {
        text: '暂不跟进',
        value: AddStaffTrack.notIntend
    }];

    ionViewDidLoad() {
        this.getAllActivityType();
        this.subscribeEvents();

        this.rosterCards.notifyOnChanges();
        document.querySelector('.roster-scroll .scroll-content')
            .addEventListener('scroll',
                () => {
                    this.rosterList = this.vs.handleScrollEvent();
                });
        this.rosterCards.changes.subscribe((res) => {
            if (this.vs && this.vs.changeIndexArr.length > 1) {
                    this.vs.updateDom();
                }
            });
    }

    ionViewWillUnload() {
        this.events.unsubscribe('roster:search');
        this.events.unsubscribe('refresh roster');
        this.events.unsubscribe('update roster');
    }

    //订阅筛选条件事件
    subscribeEvents() {
        this.events.subscribe('roster:search', (res) => {
            this.rosterFil = _.cloneDeep(res);
            this.tempFil = _.cloneDeep(this.rosterFil);
            this.getRosterList(null, true);
        });
        this.events.subscribe('refresh roster', (detail) => {
            this.switchUserStatus(detail.id);
            // this.getRosterList(null, false);
        });
        this.events.subscribe('update roster', () => {
            // this.getRosterList(null, false);
        });
    }

    //补全参数（若活动状态，活动进度为空则补充为全量条件）
    supplementRosterFil() {
        if (this.rosterFil.type.length === 0) {
            this.rosterFil.type = this.allType.map((item) => {
                return item.id
            });
        }
        if (this.rosterFil.status.length === 0) {
            this.rosterFil.status = [ActivityStatus.notStart, ActivityStatus.processing, ActivityStatus.over];
        }
        if (this.rosterFil.trackStatus.length === 0) {
            if (this.rosterFil.classify === 0) {
                this.rosterFil.trackStatus = [TrackStatus.notFollow, TrackStatus.contacted,
                    TrackStatus.notContacted, TrackStatus.notInterested,
                    TrackStatus.waitCallback, TrackStatus.overInterview,
                    TrackStatus.overPrint, TrackStatus.complete];
            } else if (this.rosterFil.classify === 1) {
                this.rosterFil.trackStatus = [AddStaffTrack.notFollow, AddStaffTrack.process, AddStaffTrack.notIntend];
            }
        }
    }

    //切换筛选条件
    switchSotrBy(val) {
        this.rosterFil.sortBy = val;
        this.isExpandSorter = false;
        this.getRosterList(null, true);
    }

    /**
     * 获取所有的活动类型
     */
    getAllActivityType() {
        this.isLoaded = false;
        this.loadingService.showLoading();
        this.activityListPro.getActivityType(this.rosterFil.classify, 0)
            .subscribe((res: Array<any>) => {
                this.allType = res;
                this.rosterFil.type = this.allType.map((item) => {
                    return item.id
                });
                this.getRosterList();
            }, err => {
                this.isLoaded = true;
                this.loadingService.dismissLoading();
            });
    }

    getRosterList(refresh = null, needLoading = false) {
        this.isLoaded = false;
        if (needLoading) {
            this.loadingService.showLoading();
        }
        this.supplementRosterFil();
        this.rosterPro.getRosterList(this.rosterFil)
            .subscribe((res: RosterItem[]) => {
                this.storeRosterList(res);
                this.isLoaded = true;
                this.totalNum = res.length;
                this.vs = new Vs(res, '.card', '.roster-scroll .scroll-content');
                this.rosterList = this.vs.initVirtualArr();
                if (refresh) {
                    refresh.complete();
                }
                setTimeout(() => {
                    this.loadingService.dismissLoading();
                }, 300);
            }, err => {
                this.isLoaded = true;
                if (refresh) {
                    refresh.complete();
                }
                this.loadingService.dismissLoading();
            });
    }

    /**
     * @function 缓存列表
     * @author daniel wu
     * @param array
     */
    storeRosterList(array: any) {
        let storeList = [];
        if (array && array.length) {
            array.map(e => {
                storeList.push({
                    client_id: e.id,
                    name: e.name,
                    sex: e.sex || ''
                });
            });
        }
        window.sessionStorage.setItem('storeRosterList', JSON.stringify(storeList));
    }

    popToActivityList() {
        this.navCtrl.popTo('ActivityListPage', {
            animate: false
        });
    }

    //切换当前试图
    changeCurrentView(num) {
        this.resetFilter();
        this.currentView = num;
        this.tempFil.classify = num;
        this.rosterFil.classify = num;
        if (num === 0) {
            this.sortByList = [{
                val: RosterSortBy.priority,
                label: '默认排序'
            }, {
                val: RosterSortBy.name,
                label: '姓名'
            }, {
                val: RosterSortBy.time,
                label: '活动开始时间'
            }];
        } else {
            this.sortByList = [{
                val: RosterSortBy.priority,
                label: '默认排序'
            }, {
                val: RosterSortBy.name,
                label: '姓名'
            }, {
                val: RosterSortBy.takeTime,
                label: '参与时间'
            }];
        }
        this.getAllActivityType();
    }

    //展示切换状态选项
    showSelectAction(customerId, index, event) {
        let innerIndex = event.innerIndex;
        let activityId = event.innerId;
        let ev = event.$event;

        let status = this.rosterList[index].activitys[innerIndex].trackStatus;
        if (this.rosterFil.classify === ActivityClassify.marketActivity) {
            this.actionButtons.forEach((item) => {
                if (status === item.value) {
                    item['cssClass'] = 'action-sheet-selected';
                } else {
                    item['cssClass'] = '';
                }
                item['handler'] = () => {
                    this.switchStatus({
                        customerId,
                        activityId,
                        trackStatus: item.value
                    }, index, innerIndex);
                }
            });
            this.adpActionSheetCtrl.create({
                title: '跟进状态',
                buttons: this.actionButtons
            }).present();
        } else {
            this.actionButtons2.forEach((item) => {
                if (status === item.value) {
                    item['cssClass'] = 'action-sheet-selected';
                } else {
                    item['cssClass'] = '';
                }
                item['handler'] = () => {
                    this.switchStatus({
                        customerId,
                        activityId,
                        trackStatus: item.value
                    }, index, innerIndex);
                }
            });
            this.adpActionSheetCtrl.create({
                title: '跟进状态',
                buttons: this.actionButtons2
            }).present();
        }
        ev.stopPropagation();
    }

    switchStatus(params, index, innerIndex) {
        this.rosterPro.switchRosterStatus(params).subscribe((res) => {
            this.rosterList[index].activitys[innerIndex].trackStatus = params.trackStatus;
        }, err => {
        });
    }

    //客户端更新 该客户符合条件的活动状态
    switchUserStatus(id) {
        this.rosterList.forEach((item) => {
            if (item.id === id) {
                item.activitys.forEach((innerItem) => {
                    if (innerItem.status === ActivityStatus.processing
                        && innerItem.trackStatus === TrackStatus.notFollow) {
                        innerItem.trackStatus = TrackStatus.contacted;
                    }
                })
            }
        })
    }

    goToRosterFilter() {
        this.navCtrl.push('RosterFilterPage', {
            tempFil: _.cloneDeep(this.tempFil)
        });
    }

    goToRosterMap() {
        this.navCtrl.push('RosterMapPage', {origin: 'roster-list'});
    }

    expandSelect() {
        this.isExpandSorter = !this.isExpandSorter;
    }

    //初始化参数
    resetFilter() {
        this.tempFil = new RosterFilterModel();
        this.rosterFil = new RosterFilterModel();
    }
}
